import {
	cloneDeep
} from 'lodash-es';
import {
	warn
} from 'vue';

import {
	LOGIN_PAGE,
	NAVIGATE_TYPE
} from '@/enums/routerEnum';

import {
	deepMerge
} from '@/utils';
import {
	isIncludesAuthRouter
} from '@/utils/router/interceptor';
import store from '../../state/modules/auth.js';

export class Navigates {
	constructor(type, options) {
		this.type = type || NAVIGATE_TYPE.NAVIGATE_TO;
		this.options = options || {};
	}

	navigate(url, options) {
		const navigateOptions = deepMerge(cloneDeep(this.options), options);
		const _options = deepMerge({
			url
		}, navigateOptions);
		switch (this.type) {
			case NAVIGATE_TYPE.NAVIGATE_TO:
				uni.navigateTo(_options);
				break;
			case NAVIGATE_TYPE.REDIRECT_TO:
				uni.redirectTo(_options);
				break;
			case NAVIGATE_TYPE.RE_LAUNCH:
				uni.reLaunch(_options);
				break;
			case NAVIGATE_TYPE.SWITCH_TAB:
				uni.switchTab(_options);
				break;
			case NAVIGATE_TYPE.NAVIGATE_BACK:
				uni.navigateBack(navigateOptions);
				break;
			default:
				warn('navigate Error');
				break;
		}
	}

	push(url, options) {
		this.type = NAVIGATE_TYPE.NAVIGATE_TO;
		this.navigate(url, options);
	}

	replace(url, options) {
		this.type = NAVIGATE_TYPE.REDIRECT_TO;
		this.navigate(url, options);
	}

	replaceAll(url, options) {
		this.type = NAVIGATE_TYPE.RE_LAUNCH;
		this.navigate(url, options);
	}

	pushTab(url, options) {
		// 微信小程序端uni.switchTab拦截无效处理
		/* #ifdef MP-WEIXIN */
		if (isIncludesAuthRouter(url)) {
			if (!store.getters.isLogin) {
				const _path = url.startsWith('/') ? url : `/${url}`;
				const pathQuery = encodeURIComponent(_path);
				this.push(`${LOGIN_PAGE}?redirect=${pathQuery}`);
			}
			return;
		}
		/* #endif */
		this.type = NAVIGATE_TYPE.SWITCH_TAB;
		this.navigate(url, options);
	}

	back(options) {
		this.type = NAVIGATE_TYPE.NAVIGATE_BACK;
		this.navigate('', options);
	}
}